package com.jgj.zxkj.lookandcheckjggroupinfo.record.nocheck;

import android.support.annotation.StringRes;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.EmptyUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jgj.zxkj.lookandcheckjggroupinfo.R;
import com.jgj.zxkj.lookandcheckjggroupinfo.constants.Constants;
import com.jgj.zxkj.lookandcheckjggroupinfo.login.UserProfile;
import com.jgj.zxkj.lookandcheckjggroupinfo.record.detail.CheckDetailDelegate;
import com.sa.all_cui.mix_core.delegate.DoggerDelegate;
import com.sa.all_cui.mix_core.net.RestClient;
import com.sa.all_cui.mix_core.net.callback.IError;
import com.sa.all_cui.mix_core.net.callback.ISuccess;
import com.sa.all_cui.mix_core.utils.storage.simpledisk.DiskLruCacheHelper;
import com.sa.all_cui.mix_ui.recycler.DataConvert;
import com.sa.all_cui.mix_ui.recycler.MultipleItemEntity;
import com.sa.all_cui.mix_ui.refresh.PagingBean;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by all-cui on 2017/11/2.
 */

@SuppressWarnings("WeakerAccess")
public class RefreshLoadMoreHandler implements SwipeRefreshLayout.OnRefreshListener,
        BaseQuickAdapter.RequestLoadMoreListener {
    private final SwipeRefreshLayout mRefreshLayout;
    private final PagingBean BEAN;
    private final RecyclerView RECYCLERVIEW;
    private SimpleRecyclerAdapter mAdapter = null;
    private final DataConvert CONVERT;
    private String mUrl = null;
    private int mStatus = 0;
    private DoggerDelegate mDelegate = null;

    private RefreshLoadMoreHandler(SwipeRefreshLayout refreshLayout,
                                   RecyclerView recyclerView, DataConvert convert,
                                   PagingBean bean) {
        this.mRefreshLayout = refreshLayout;
        mRefreshLayout.setOnRefreshListener(this);
        this.BEAN = bean;
        this.RECYCLERVIEW = recyclerView;
        this.CONVERT = convert;
        mAdapter = SimpleRecyclerAdapter.create(R.layout.item_no_check);
        RECYCLERVIEW.setAdapter(mAdapter);
        mAdapter.bindToRecyclerView(RECYCLERVIEW);
    }

    //简单工厂模式
    public static RefreshLoadMoreHandler create(SwipeRefreshLayout refreshLayout,
                                                RecyclerView recyclerView,
                                                DataConvert convert) {
        return new RefreshLoadMoreHandler(refreshLayout, recyclerView, convert, new PagingBean());
    }

    public final RefreshLoadMoreHandler setPageUrl(String url) {
        this.mUrl = url;
        return this;
    }

    public final RefreshLoadMoreHandler setStatus(int status) {
        this.mStatus = status;
        return this;
    }

    public final RefreshLoadMoreHandler setDelegate(DoggerDelegate delegate) {
        this.mDelegate = delegate;
        return this;
    }


    private void handlePageSuccess(String response) {
        LogUtils.i(response);
        final List<MultipleItemEntity> pageDatas = getMultipleItemEntities(response);
        showError(pageDatas, true);
        mAdapter.setNewData(pageDatas);
        mAdapter.setOnLoadMoreListener(RefreshLoadMoreHandler.this, RECYCLERVIEW);
        BEAN.setPageIndex(0);
        mAdapter.loadMoreComplete();
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                final String id = mAdapter.getData().get(position).getField(PageDataType.ID);
                CheckDetailDelegate detailDelegate = CheckDetailDelegate.newInstance(id);
                mDelegate.getParentDelegate().getSupportDelegate().start(detailDelegate);
            }
        });
        //RECYCLERVIEW.addOnItemTouchListener(NoCheckItemClickListener.create(mDelegate, mAdapter));
    }

    private void showError(List<MultipleItemEntity> pageDatas, boolean isEmpty) {
        if (isEmpty) {
            //显示空数据提示页面
            if (EmptyUtils.isEmpty(pageDatas)) {
                setTipText(R.string.empty_tip);
            }
        } else {
            setTipText(R.string.net_connect_fail_tip);
        }

    }

    private void setTipText(@StringRes int resId) {
        View view = View.inflate(RECYCLERVIEW.getContext(), R.layout.layout_error_tip, null);
        mAdapter.setEmptyView(view);
        AppCompatTextView tip = (AppCompatTextView)view.findViewById(R.id.tv_error_tip);
        tip.setText(resId);
    }

    private List<MultipleItemEntity> getMultipleItemEntities(String response) {
        mRefreshLayout.setRefreshing(false);
        final JSONObject data = JSON.parseObject(response);
        if (!data.getString("success").equals(Constants.SUCCESS_FLAG)){
            return null;
        }
        CONVERT.clear();
        final List<MultipleItemEntity> pageDatas = CONVERT.setJsonData(response).convert();
        BEAN.setTotal(data.getInteger("total"));
        BEAN.setPageSize(data.getInteger("page_size"));
        return pageDatas;
    }

    @SuppressWarnings("UnnecessaryReturnStatement")
    private void checkNet() {
        if (!NetworkUtils.isConnected()) {
            LogUtils.i("暂无网络");
            showError(null, false);
            return;
        }
    }

    public void retainPageFirstNet() {
        checkNet();
        UserProfile profile = DiskLruCacheHelper.getInstance().getAsSerializable(Constants.USER_PROFILE);
        RestClient.builder()
                .url(mUrl)
                .loader(mRefreshLayout.getContext())
                .params("start", 0)
                .params("status", mStatus)
                .params("permission", profile.getPermission())
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        handlePageSuccess(response);
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        mRefreshLayout.setRefreshing(false);
                    }
                })
                .build()
                .get();
    }



    private void retainPagingNet() {
        checkNet();
        UserProfile profile = DiskLruCacheHelper.getInstance().getAsSerializable(Constants.USER_PROFILE);
        final int pageIndex = BEAN.getPageIndex() + 1;
        //当列表的item数目大于服务器获取item总数量或者列表的item数量小于一页item，加载更多结束
        LogUtils.i("index:" + pageIndex + "\r\ntotalPageIndex:" + BEAN.getTotal() + "\r\n");
        if (pageIndex == BEAN.getTotal()) {
            mAdapter.loadMoreEnd(false);
        } else if (pageIndex < BEAN.getTotal()) {
            RestClient.builder()
                    .url(mUrl)
                    .params("status", mStatus)
                    .params("start", BEAN.getPageIndex() + 1)
                    .params("permission", profile.getPermission())
                    .success(new ISuccess() {
                        @Override
                        public void onSuccess(String response) {
                            final ArrayList<MultipleItemEntity> pageResList = CONVERT.setJsonData(response).convert();
                            if (EmptyUtils.isNotEmpty(pageResList)) {
                                mAdapter.setNewData(pageResList);
                                mAdapter.loadMoreComplete();
                                BEAN.addIndex();
                                final JSONObject data = JSON.parseObject(response);
                                BEAN.setPageSize(data.getInteger("page_size"));
                            } else {
                                mAdapter.loadMoreFail();
                            }
                        }
                    })
                    .error(new IError() {
                        @Override
                        public void onError(int code, String msg) {
                            mAdapter.loadMoreFail();
                        }
                    })
                    .build()
                    .get();
        }
    }

    @Override
    public void onRefresh() {
        retainPageFirstNet();
    }

    @Override
    public void onLoadMoreRequested() {
        retainPagingNet();
    }

}
